package net.cl.mvc.dispatcher;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import net.cl.mvc.Globals;
import net.cl.mvc.config.ActionMapping;
import net.cl.mvc.config.Configuration;
import net.cl.mvc.wrappers.ActionContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DispatcherFilter implements Filter {

	private static final Log log = LogFactory.getLog(DispatcherFilter.class);
	private FilterConfig filterConfig;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		Configuration.initFilterConfig(this.filterConfig);
		ActionContext.setServletContext(this.filterConfig.getServletContext());
		ActionMapping.initMapping();
		log.debug("DispatcherFilter has started.");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		log.debug("DispatcherFilter doFilter.");
		String s = Dispatcher.invoke(request, response);
		if (request.getAttribute(Globals.NEXT_CHAIN_KEY) != null)
			chain.doFilter(request, response);
		else {
			if (s != null) {
				RequestDispatcher rd = request.getRequestDispatcher(s);
				rd.forward(request, response);
			}
		}
	}

	@Override
	public void destroy() {
		filterConfig = null;
		log.debug("DispatcherFilter has destroyed.");
	}

}
